package com.emagic.manage.modules.splashmodule.activity;

import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.emagic.manage.R;
import com.emagic.manage.biz.UserProfile;
import com.emagic.manage.common.preference.UserSharedPreference;
import com.emagic.manage.common.ui.base.BaseActivity;
import com.emagic.manage.modules.splashmodule.presenter.SplashPresenter;
import com.emagic.manage.modules.splashmodule.view.SplashView;
import com.emagic.manage.utils.ToastUtil;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.xitaiinfo.library.compat.errorview.ErrorView;

import java.util.concurrent.atomic.AtomicInteger;

import javax.inject.Inject;

/**
 * 启动界面
 *
 * @author baoy
 * @version 1.0
 */
public class SplashActivity extends BaseActivity implements SplashView {

    private static final String TAG = SplashActivity.class.getSimpleName();

    private static final int sleepTime = 2000;

    private long start;

    @Inject
    SplashPresenter mPresenter;

    private UserProfile userProfile;

    private AtomicInteger grandCount;

    /*
        睡眠两秒
     */
    private void sleep(long start) {
        long costTime = System.currentTimeMillis() - start;
        //等待sleepTime时长
        if (sleepTime - costTime > 0) {
            try {
                Thread.sleep(sleepTime - costTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void jumpToLoginAfterSleep() {
        new Thread(() -> {
            sleep(start);//睡2秒跳转到登录页面,并销毁当前页面
            getNavigator().navigateToLoginActivity(getContext(), "");
            finish();
        }).start();
    }

    private void splash() {
        start = System.currentTimeMillis(); //获取开始时间
        //判断是否第一次使用APP
        UserSharedPreference userSharedPreference = UserSharedPreference.getInstance(getContext());
        userProfile = userSharedPreference.getUserProfile();

        if (userProfile == null) {//进入手动登录
            jumpToLoginAfterSleep();
        } else {
            mPresenter.login(userProfile.getAccount(), userProfile.getPwd());
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestFeatureFullScreen();
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);

        final String appName = getString(R.string.app_name);
        mPresenter.attachView(this);

        grandCount = new AtomicInteger(0);

        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .requestEach(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CALL_PHONE)
                .subscribe(permission -> {
                    int count = grandCount.addAndGet(1);
                    if (permission.granted) {
                        if (count == 5) {
                            splash();
                        }
                    } else {
                        if (permission.name.equals(Manifest.permission.CAMERA)) {
                            ToastUtil.showMiddleScreenToast(getContext(), "请在设置-应用-" + appName + "-权限管理中开启摄像头权限");
                        } else if (permission.name.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            ToastUtil.showMiddleScreenToast(getContext(), "请在设置-应用-" + appName + "-权限管理中开启存储空间信息权限");
                        } else if (permission.name.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                            ToastUtil.showMiddleScreenToast(getContext(), "请在设置-应用-" + appName + "-权限管理中开启定位权限");
                        } else if (permission.name.equals(Manifest.permission.RECORD_AUDIO)) {
                            ToastUtil.showMiddleScreenToast(getContext(), "请在设置-应用-" + appName + "-权限管理中开启录音权限");
                        } else if (permission.name.equals(Manifest.permission.CALL_PHONE)) {
                            ToastUtil.showMiddleScreenToast(getContext(), "请在设置-应用-" + appName + "-权限管理中开启拨打电话权限");
                        }
                        if (count == 5) {
                            splash();
                        }
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPresenter.onPause();
    }


    @Override
    public void loginSuccess() {
        //登录成功跳转主页,并销毁当前页面
        new Thread(() -> {
            sleep(start);
            getNavigator().navigateToMain(getContext());
            finish();
        }).start();
    }

    @Override
    public void loginFail(String message) {
        //显示错误信息,并跳转到登录页面
        String nickName = null;
        if (userProfile != null) {
            nickName = userProfile.getAccount();
        }
        getNavigator().navigateToLoginActivity(getContext(), nickName);
        finish();
    }

    @Override
    public Context getContext() {
        return SplashActivity.this;
    }

    @Override
    public void showLoadingView() {

    }

    @Override
    public void showEmptyView(ErrorView.Config errorConfig, ErrorView.OnRetryListener onRetryListener) {

    }

    @Override
    public void showErrorView(Throwable throwable, ErrorView.Config errorConfig, ErrorView.OnRetryListener onRetryListener) {

    }

    @Override
    public void onLoadingComplete() {

    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    }
}
